<template>
    <div class="message">
        <input type="text" placeholder="短信验证码" ref="smsCode" :value="value" v-betterInput="betterInput" @change="bindValue" @input="bindValue">
        <span class="getCode" :class="{waiting:waiting}" @click="getSmsCode">{{hint}}</span>
    </div>
</template>
<script>
/*
    获取短信验证码需要手机号和图形验证
*/
export default {
    data() {
        return {
            hint: '获取验证码',
            waiting: false
        }
    },
    props: {
        value: null,
        mobile: null,
        picCode: null,
        betterInput: {
            default: 0
        },
        custom: {
            default: false
        }
    },
    methods: {
        getSmsCode() {
            if (this.waiting) return;
            if (this.custom) {
                this.$emit('getSms')
                this.waiting = true;
                return
            } else if (this.picCode.trim().length == 0) {
                $toast.show('请先输入图形验证码');
                return;
            }
            this.waiting = true;
            $ajax.captcha.getSmsCode({ mobile: this.mobile, picCode: this.picCode }).then(res => {
                $toast.show(res.data.msg);
                if (res.data.code == 'S') {
                    this.wait()
                } else {
                    //获取短信验证码失败，需要重新获取图形验证码
                    this.reauth();
                }
            }).catch(err => {
                this.reauth();
            })
        },
        bindValue(e) {
            this.$emit('input', e.target.value);
        },
        wait() {
            this.waiting = true
            var seconds = 60;
            this.hint = seconds + 's';
            var timer = setInterval(() => {
                seconds--;
                if (seconds <= 0) {
                    this.hint = '获取验证码';
                    this.waiting = false;
                    clearInterval(timer);
                } else {
                    this.hint = seconds + 's';
                }
            }, 1000);
        },
        clearWait() {
            this.waiting = false
        },
        reauth() {
            //重新获取图形验证
            this.$emit('fail');
            this.waiting = false;
        }
    }
}
</script>
<style lang="scss" scoped>
@import '../../asset/scss/mixin/export.scss';
.inputLeft {
    @include inputLeft;
}

.inputLine {
    @include inputLine;
}

.getCode {
    @include getCode;
}
</style>